-- SPDX-FileCopyrightText: Adam Evyčędo
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

---@diagnostic disable-next-line: unused-local, lowercase-global
function getAlerts(stopID, stopCode, tripID, lineID)
	local http = require("http")
	local json = require("json")

	local error_struct = {
		httpResponseCode=0,
		message="",
		willNextRequestFail=false
	}

	local rbls_raw = ""
	local i = 0
	for m in string.gmatch(stopCode, "([^|]+)") do
		if i == 1 then
			rbls_raw = m
			break
		end
		i = i + 1
	end

	local rbls = {}
	i = 1
	for m in string.gmatch(rbls_raw, "([^,]+)") do
		rbls[i] = m
		i = i + 1
	end

	local alerts = {}

	for _, rbl in ipairs(rbls) do
		local response, error_message = http.get("https://www.wienerlinien.at/ogd_realtime/trafficInfoList?", {
			query = "relatedStop=" .. rbl,
			timeout = "30s"
		})

		if response == nil then
			error_struct.message = "while getting alerts: " .. error_message
			local error_json, _ = json.encode(error_struct)
			return "", error_json
		end

		if response.status_code ~= 200 then
			error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
			error_struct.httpResponseCode = response.status_code
			error_struct.willNextRequestFail = true
			local error_json, _ = json.encode(error_struct)
			return "", error_json
		end

		---@diagnostic disable-next-line: redefined-local
		local struct, error_message = json.decode(response.body)

		if struct == nil then
			error_struct.message = "while decoding alerts: " .. error_message
			local error_json, _ = json.encode(error_struct)
			return "", error_json
		end


		for j, entry in ipairs(struct.data.trafficInfos) do
		  alerts[j] = {
		    timeRanges={
		    	{
		    		startDate=string.sub(entry.time.start, 1, 26) .. ":" .. string.sub(entry.time.start, 27, 28),
		    		endDate=string.sub(entry.time["end"], 1, 26) .. ":" .. string.sub(entry.time["end"], 27, 28)
		    	}
		    },
		    headers={de_AT=entry.title},
		    descriptions={de_AT=entry.description},
		    cause=0,
		    effect=0
		  }
		end
	end

	---@diagnostic disable-next-line: redefined-local
	local result, error_message = json.encode(alerts)

	if result == nil then
		error_struct.message = "while encoding result: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	return result, ""
end
